package dbops

import (
	"GoStreamVideoWebsite/api/defs"
	"errors"
	"log"
	"strconv"
	"sync"
)

//用于处理session与db的操作，因为这不属于api业务逻辑上的操作 所以分开

func WriteSession(sid string, ttl int64, username string) error {
	lock.Lock()
	defer lock.Unlock()
	ttlstr := strconv.FormatInt(ttl, 10)
	var sess defs.Sessions = defs.Sessions{
		SessionId: sid,
		TTL:       ttlstr,
		Username:  username,
	}
	if err := dbConn.Create(&sess).Error; err != nil {
		return err
	}
	return nil
}

func RetrieveSession(sid string) (*defs.SimpleSession, error) {
	lock.Lock()
	defer lock.Unlock()
	ss := &defs.SimpleSession{}
	temp := &defs.Sessions{}
	if dbConn.Where("session_id=?", sid).First(temp).RecordNotFound() {
		return nil, errors.New("Not Found Session")
	}
	ss.TTL, _ = strconv.ParseInt(temp.TTL, 10, 64)
	ss.Username = temp.Username
	return ss, nil
}
func RetrieveAllSession() (*sync.Map, error) {
	lock.Lock()
	defer lock.Unlock()
	var sessions []*defs.Sessions
	if err := dbConn.Find(&sessions).Error; err != nil {
		return nil, err
	}
	var sessmap *sync.Map
	for i := range sessions {
		ttl, _ := strconv.ParseInt(sessions[i].TTL, 10, 64)
		sessmap.Store(sessions[i].SessionId, &defs.SimpleSession{
			Username: sessions[i].Username,
			TTL:      ttl,
		})
		log.Printf("session id %s, ttl %d", sessions[i].SessionId, ttl)
	}
	return sessmap, nil
}
func DeleteSession(sid string) error {
	lock.Lock()
	defer lock.Unlock()
	err := dbConn.Debug().Where("session_id=?", sid).Delete(defs.Sessions{}).Error
	return err
}
